/*
 * FileName: MethodHandleTest.java
 * Author:   zzw
 * Date:     2018年11月06日
 * Description:
 */
package com.zzw.hotspot.method;

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Method;

/**
 * 〈〉<br>
 * 〈〉
 *
 * @author zzw
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本]（可选）
 */
public class MethodHandleTest {
    private static void bar(Object o) {
        System.out.println("bar...");
    }

    public static MethodHandles.Lookup lookup() {
        return MethodHandles.lookup();
    }

    public static void main(String[] args) throws Throwable {
        // 获取方法句柄的不同方式
        MethodHandles.Lookup l = MethodHandleTest.lookup(); // 具备 Foo 类的访问权限
        Method m = MethodHandleTest.class.getDeclaredMethod("bar", Object.class);
        MethodHandle mh0 = l.unreflect(m);

        MethodType t = MethodType.methodType(void.class, Object.class);
        MethodHandle mh1 = l.findStatic(MethodHandleTest.class, "bar", t);

        MethodHandles.Lookup l2 = MethodHandles.lookup();
        MethodType t2 = MethodType.methodType(void.class, Object.class);
        MethodHandle mh = l2.findVirtual(MethodHandleTest.class, "bar", t2);

        long current = System.currentTimeMillis();
        for (int i = 1; i <= 2_000_000_000; i++) {
            if (i % 100_000_000 == 0) {
                long temp = System.currentTimeMillis();
                System.out.println(temp - current);
                current = temp;
            }
            mh.invokeExact(new MethodHandleTest(), new Object());
        }
    }
}
